;;problem  2 fibo sum
(print
 (do ((n 0 (+ 1 n))
      (cur 0 next)
      (next 1 (+ cur next))
      (sum 0 (if (evenp cur) (+ sum cur) sum)))
     ((< 1000000 cur ) sum)))




;;problem 3 largest prime of 317584931803
(print 
 (do ((div 2 (+ div 1))
      (n 317584931803 
	 (if (zerop (mod n div))
	     (/ n div)
	     n)))
     ((< (/ n 2) div) n)))

(print
 (do ((nums 0)
      (i 999 (1- i)))
     ((< i 1) nums) 
   (do ((j 999 (1- j)))
       ((< j 1) )
     (if (palindrom (* i j))
	 (setq nums (max (* i j) nums))))))


;;problem 4
;;(defun number-at (number poz)
;; (mod 
;;  (do ((i 1 (1+ i))
;;       (n number (/ (- n (mod n 10))  10)))
;;      ((= i poz) n) ) 10))

(defun pow (x n)
  (cond ((= n 0) 1)
	(t (* x (pow x (- n 1))))))

(defun drop-digit (n)
  (/ (- n (mod n 10)) 10))

(defun drop-first-digit (n)
  (mod n (pow 10 (- (digits n) 1))))

(defun first-digit (n)
  (/ (- n (drop-first-digit n)) (pow 10 (- (digits n) 1))))

(defun last-digit (n)
  (mod n 10))
  
(defun number-at (n poz)
  (cond 
    ((= poz 0) 0)
    ((= poz 1) (mod n 10))
    (t (number-at (drop-digit n) (- poz 1)))))

(defun digits-inner (n i)
  (cond ((< n 10) i)
	(t (+ 1 (digits-inner (drop-digit n) i )))))

(defun digits (n)
  (digits-inner n 1))

(defun palindromp (n)
  (cond ((= 1 (digits n)) T)
	((not (eq (first-digit n) (last-digit n))) nil)
	(t (palindromp (drop-digit (drop-first-digit n))))))



;;(defun palindromp2 (n)
;;  (do
;;   ((i 0 (floor (/ (digits n) 2)))
;;    ((eq (number-at n (1+ i)) (number-at n (- (digits n) i)))))
;;))

(defun palindrom (n)
  (equal (format nil "~a" n) 
	 (reverse (format nil "~a" n))))
